import { MetaMaskSDK } from '@metamask/sdk';

import type { EIP6963ProviderDetail } from '../metamask';
import type { SDKProvider } from '@metamask/sdk';

let provider: EIP6963ProviderDetail | undefined | SDKProvider= undefined;
let account = '';
let connectionError: unknown;
const getProviderAndAccount = async () => {
    if (window.ethereum) {
        try {
            // Запрос доступа к MetaMask
            const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }) as string[];
            provider = window.ethereum;
            account = accounts[0];

        } catch (error) {
            console.error((error as Error).message);
            connectionError = error;
        }
    } else {
        const MMSDK = new MetaMaskSDK({
            dappMetadata: {
                name: 'NFT Barter',
                url: window.location.href,
            },
            injectProvider: true,
        });
        try {
            const accounts = await MMSDK.connect();

            provider = MMSDK.getProvider();
            account = accounts[0];
        } catch (error) {
            connectionError = error;
        }
    }
};

const storeData = {
    get provider () { return provider; },
    get account () { return account.toUpperCase(); },
    get error () { return connectionError; },
    getProviderAndAccount,
};

export const store = {
    value: () => storeData,
    subscribe: (callback: ()=> void) => {

        callback();

        return () => {};
    },
};